import os
import sys
import platform
from pyppeteer.chromium_downloader import download_chromium, REVISION, DOWNLOADS_FOLDER
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def get_chromium_mirror():
    """获取适合当前系统的 Chromium 镜像源"""
    system = platform.system().lower()
    if system == 'windows':
        return 'https://cdn.npmmirror.com/binaries/chromium-browser-snapshots/Win_x64'
    elif system == 'darwin':
        return 'https://cdn.npmmirror.com/binaries/chromium-browser-snapshots/Mac'
    else:  # linux
        return 'https://cdn.npmmirror.com/binaries/chromium-browser-snapshots/Linux_x64'

def setup_chromium():
    """设置并下载 Chromium"""
    try:
        # 设置环境变量
        mirror = get_chromium_mirror()
        os.environ['PYPPETEER_DOWNLOAD_HOST'] = mirror
        logger.info(f"使用镜像源: {mirror}")

        # 确保下载目录存在
        if not os.path.exists(DOWNLOADS_FOLDER):
            os.makedirs(DOWNLOADS_FOLDER)
            logger.info(f"创建下载目录: {DOWNLOADS_FOLDER}")

        # 尝试下载 Chromium
        try:
            download_chromium()
            logger.info("Chromium 下载成功")
            return True
        except Exception as e:
            logger.error(f"从主镜像源下载失败: {str(e)}")
            
            # 尝试备用镜像源
            backup_mirrors = [
                'https://npm.taobao.org/mirrors/chromium-browser-snapshots',
                'https://storage.googleapis.com/chromium-browser-snapshots',
                'https://registry.npmmirror.com/-/binary/chromium-browser-snapshots'
            ]
            
            for mirror in backup_mirrors:
                try:
                    logger.info(f"尝试备用镜像源: {mirror}")
                    os.environ['PYPPETEER_DOWNLOAD_HOST'] = mirror
                    download_chromium()
                    logger.info(f"从备用镜像源 {mirror} 下载成功")
                    return True
                except Exception as e:
                    logger.error(f"从备用镜像源 {mirror} 下载失败: {str(e)}")
                    continue
            
            logger.error("所有镜像源都下载失败")
            return False
            
    except Exception as e:
        logger.error(f"设置 Chromium 时发生错误: {str(e)}")
        return False

# 执行设置
if not setup_chromium():
    logger.error("""
Chromium 下载失败！请尝试以下解决方案：

1. 检查网络连接
2. 手动下载 Chromium：
   - 访问 https://registry.npmmirror.com/-/binary/chromium-browser-snapshots
   - 下载对应版本的 chrome-win.zip
   - 解压到 ~/.local/share/pyppeteer/local-chromium/ 目录

3. 或者尝试使用其他版本的 pyppeteer：
   pip install pyppeteer==1.0.2
""")
    sys.exit(1) 